<?php
if (!file_exists('../install.lock')) {
    header('Location: ../install.php');
    exit;
}

require_once 'config.php';
require_once 'alipay.php';

$settings = getSettings();
$error = '';
$order = null;
$qr_code = '';

$order_no = $_GET['order_no'] ?? '';

if (empty($order_no)) {
    header('Location: index.php');
    exit;
}

// 获取订单信息
$stmt = $pdo->prepare("SELECT o.*, p.name as product_name, p.description as product_description, p.duration_type, p.duration_value FROM orders o LEFT JOIN products p ON o.product_id = p.id WHERE o.order_no = ?");
$stmt->execute([$order_no]);
$order = $stmt->fetch();

if (!$order) {
    header('Location: index.php');
    exit;
}

// 如果订单已支付，跳转到成功页面
if ($order['status'] === 'paid') {
    header('Location: success.php?order_no=' . $order_no);
    exit;
}

// 如果订单已过期，跳转到失败页面
if ($order['status'] === 'expired') {
    header('Location: failed.php?order_no=' . $order_no);
    exit;
}

// 生成支付宝二维码
if ($order['status'] === 'pending') {
    $alipay = new AlipayF2F(
        ALIPAY_APP_ID,
        ALIPAY_PRIVATE_KEY,
        ALIPAY_PUBLIC_KEY,
        ALIPAY_NOTIFY_URL,
        ALIPAY_RETURN_URL
    );
    
    // 拼接支付宝商品说明，格式：网站标题-商品名(时长+类型)-数量-订单号
    $type_map = [
        'minute' => '分钟',
        'hour' => '小时',
        'day' => '天',
        'week' => '周',
        'month' => '月',
        'season' => '季',
        'quarter' => '季',
        'year' => '年',
        'forever' => '永久',
        '分钟' => '分钟',
        '小时' => '小时',
        '天' => '天',
        '周' => '周',
        '月' => '月',
        '季' => '季',
        '年' => '年',
        '永久' => '永久'
    ];
    $type = $type_map[$order['duration_type']] ?? $order['duration_type'];
    if ($order['duration_type'] === 'forever' || $order['duration_type'] === '永久') {
        $product_str = $order['product_name'] . '(' . $type . ')';
    } else if (!empty($order['duration_value']) && !empty($type)) {
        $product_str = $order['product_name'] . '(' . $order['duration_value'] . $type . ')';
    } else {
        $product_str = $order['product_name'];
    }
    $subject = ($settings['title'] ?? '卡密购买') . '-' . $product_str . '-数量×' . $order['quantity'] . '-订单编号' . $order['order_no'];
    $qr_code = $alipay->createQRCode($order_no, $order['total_amount'], $subject);
    
    if (!$qr_code) {
        $error = '生成支付二维码失败，请稍后重试';
    }
}

// 订单超时时间（秒）
$timeout = 5 * 60; // 5分钟
$created_time = strtotime($order['created_at']);
$now = time();
$time_left = max(0, $timeout - ($now - $created_time));
?>
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
    <title><?php echo htmlspecialchars($settings['title'] ?? '卡密购买'); ?> - 支付订单</title>
    <link rel="shortcut icon" type="image/x-icon" href="../assets/favicon.ico">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-touch-fullscreen" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="default">
    <link rel="stylesheet" type="text/css" href="../assets/css/materialdesignicons.min.css">
    <link rel="stylesheet" type="text/css" href="../assets/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="../assets/css/animate.min.css">
    <link rel="stylesheet" type="text/css" href="../assets/css/style.min.css">
    <style>
        .payment-container {
            max-width: 100%;
            margin: 0;
        }
        .qr-code-container {
            text-align: center;
            padding: 30px;
            background: #f8f9fa;
            border-radius: 10px;
            margin: 20px 0;
        }
        .qr-code {
            max-width: 200px;
            margin: 0 auto;
        }
        .order-info {
            background: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .countdown {
            font-size: 24px;
            font-weight: bold;
            color: #dc3545;
        }
        .payment-steps {
            background: white;
            border-radius: 10px;
            padding: 20px;
            margin-top: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .mdi {
            font-family: "Material Design Icons" !important;
            font-style: normal;
            font-weight: normal;
            speak: never;
            display: inline-block;
            text-decoration: inherit;
            text-align: center;
        }
        .mdi.text-primary { color: #0d6efd !important; }
        .mdi.text-success { color: #198754 !important; }
        .mdi.text-warning { color: #ffc107 !important; }
        .mdi.text-info { color: #0dcaf0 !important; }
        .mdi.text-danger { color: #dc3545 !important; }
    </style>
</head>

<body>
<!--页面loading-->
<div id="lyear-preloader" class="loading">
    <div class="ctn-preloader">
        <div class="round_spinner">
            <div class="spinner"></div>
            <img src="../assets/images/loading-logo.png" alt="">
        </div>
    </div>
</div>
<!--页面loading end-->

<div class="lyear-layout-web">
    <div class="lyear-layout-container">
        <!-- 导航栏 -->
        <nav class="navbar navbar-expand-lg navbar-light bg-white border-bottom w-100" style="margin:0;padding:0;">
            <div class="container-fluid px-4">
                <a class="navbar-brand" href="index.php" style="text-align:left;">
                    <?php echo htmlspecialchars($settings['title'] ?? '卡密购买'); ?>
                </a>
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="collapse navbar-collapse" id="navbarNav">
                    <ul class="navbar-nav ms-auto">
                        <li class="nav-item">
                            <a class="nav-link" href="../index.php">返回首页</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="orders.php">我的订单</a>
                        </li>
                    </ul>
                </div>
            </div>
        </nav>
        
        <!--页面主要内容-->
        <main class="lyear-layout-content">
            <div class="container p-t-15">
                <div class="row justify-content-center mx-0">
                    <div class="col-lg-6 col-md-8 mx-auto">
                        <?php if ($error): ?>
                            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                <strong>错误！</strong> <?php echo $error; ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                            </div>
                        <?php endif; ?>
                        <div class="card mb-4">
                            <div class="card-body">
                                <h4 class="mb-3"><i class="mdi mdi-receipt"></i> 订单信息</h4>
                                <p class="mb-1"><strong>订单号：</strong><?php echo htmlspecialchars($order['order_no']); ?></p>
                                <p class="mb-1"><strong>商品名称：</strong><?php
                                $type_map = [
                                    'minute' => '分钟',
                                    'hour' => '小时',
                                    'day' => '天',
                                    'week' => '周',
                                    'month' => '月',
                                    'season' => '季',
                                    'quarter' => '季',
                                    'year' => '年',
                                    'forever' => '永久',
                                    '分钟' => '分钟',
                                    '小时' => '小时',
                                    '天' => '天',
                                    '周' => '周',
                                    '月' => '月',
                                    '季' => '季',
                                    '年' => '年',
                                    '永久' => '永久'
                                ];
                                $type = $type_map[$order['duration_type']] ?? $order['duration_type'];
                                if ($order['duration_type'] === 'forever' || $order['duration_type'] === '永久') {
                                    echo htmlspecialchars($order['product_name']) . '';
                                } else if (!empty($order['duration_value']) && !empty($type)) {
                                    echo htmlspecialchars($order['product_name']) . '(' . $order['duration_value'] . $type . ')';
                                } else {
                                    echo htmlspecialchars($order['product_name']);
                                }
                                ?></p>
                                <p class="mb-1"><strong>购买数量：</strong><?php echo $order['quantity']; ?> 张</p>
                                <p class="mb-1"><strong>订单金额：</strong><span class="text-danger fw-bold">￥<?php echo number_format($order['total_amount'], 2); ?></span></p>
                                <p class="mb-0"><strong>创建时间：</strong><?php echo date('Y-m-d H:i:s', strtotime($order['created_at'])); ?></p>
                            </div>
                        </div>
                        <?php if ($qr_code && !$error): ?>
                            <div class="card mb-4">
                                <div class="card-body text-center">
                                    <div class="mb-3">
                                        <span class="badge bg-danger fs-4 py-2 px-4" id="countdown">05:00</span>
                                        <span class="text-muted ms-2">支付剩余时间</span>
                                    </div>
                                    <h5 class="mb-3"><i class="mdi mdi-qrcode"></i> 请使用支付宝扫码支付</h5>
                                    <div class="mb-3">
                                        <img src="https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=<?php echo urlencode($qr_code); ?>" alt="支付二维码" class="img-fluid rounded">
                                    </div>
                                    <p class="mt-3 text-muted">请使用支付宝APP扫描上方二维码完成支付</p>
                                </div>
                            </div>
                            <div class="card mb-4">
                                <div class="card-body">
                                    <h5 class="mb-3"><i class="mdi mdi-information-outline"></i> 支付步骤</h5>
                                    <div class="row text-center">
                                        <div class="col-6 col-md-3 mb-3">
                                            <i class="mdi mdi-cellphone mdi-36px text-primary"></i>
                                            <h6 class="mt-2">打开支付宝</h6>
                                            <p class="text-muted small">在手机上打开支付宝APP</p>
                                        </div>
                                        <div class="col-6 col-md-3 mb-3">
                                            <i class="mdi mdi-qrcode-scan mdi-36px text-success"></i>
                                            <h6 class="mt-2">扫描二维码</h6>
                                            <p class="text-muted small">点击扫一扫，扫描上方二维码</p>
                                        </div>
                                        <div class="col-6 col-md-3 mb-3">
                                            <i class="mdi mdi-credit-card-check mdi-36px text-warning"></i>
                                            <h6 class="mt-2">确认支付</h6>
                                            <p class="text-muted small">确认订单信息并完成支付</p>
                                        </div>
                                        <div class="col-6 col-md-3 mb-3">
                                            <i class="mdi mdi-check-circle mdi-36px text-info"></i>
                                            <h6 class="mt-2">等待发货</h6>
                                            <p class="text-muted small">支付成功后自动发送卡密</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="text-center mb-4">
                                <button type="button" class="btn btn-outline-primary" onclick="checkPaymentStatus(true)">
                                    <i class="mdi mdi-refresh"></i> 检查支付状态
                                </button>
                                <p class="text-muted mt-2">支付完成后请点击按钮检查状态，或等待自动跳转</p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>

<script src="../assets/js/jquery.min.js"></script>
<script src="../assets/js/popper.min.js"></script>
<script src="../assets/js/bootstrap.min.js"></script>
<script src="../assets/js/perfect-scrollbar.min.js"></script>
<script src="../assets/js/main.min.js"></script>
<script>
// 倒计时功能
let timeLeft = <?php echo $time_left; ?>; // 由后端输出剩余秒数
const countdownElement = document.getElementById('countdown');

function updateCountdown() {
    const minutes = Math.floor(timeLeft / 60);
    const seconds = timeLeft % 60;
    countdownElement.textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
    
    if (timeLeft <= 0) {
        // 时间到，跳转到失败页面
        window.location.href = 'failed.php?order_no=<?php echo $order_no; ?>';
        return;
    }
    
    timeLeft--;
    setTimeout(updateCountdown, 1000);
}

// 检查支付状态
function checkPaymentStatus(showAlert = false) {
    $.ajax({
        url: 'check_payment.php',
        method: 'POST',
        data: { order_no: '<?php echo $order_no; ?>' },
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                if (response.status === 'paid') {
                    window.location.href = 'success.php?order_no=<?php echo $order_no; ?>';
                } else if (showAlert) {
                    alert('支付尚未完成，请稍后再试');
                }
            } else if (showAlert) {
                alert('检查支付状态失败：' + response.message);
            }
        },
        error: function() {
            if (showAlert) {
                alert('网络错误，请稍后重试');
            }
        }
    });
}

// 自动检查支付状态（每10秒检查一次）
setInterval(function() {
    checkPaymentStatus(false);
}, 10000);

// 启动倒计时
updateCountdown();
</script>
</body>
</html> 